package com.okilo.online.app.tools.manager

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction

/**
 * Fragment导航管理器
 * 提供Fragment的添加、替换、显示、隐藏、移除等操作，支持返回栈管理
 */
class OkiloFragmentNavigator(private val fragmentManager: FragmentManager) {

    /**
     * 安全提交Fragment事务（始终允许状态丢失）
     */
    private fun FragmentTransaction.safeCommit() {
        commitAllowingStateLoss()
    }

    /**
     * 添加并显示Fragment，隐藏其他Fragment
     * @param containerId 容器ID
     * @param fragment 要添加的Fragment实例
     */
    fun addFragment(containerId: Int, fragment: Fragment) {
        val transaction = fragmentManager.beginTransaction()

        // 隐藏所有已添加的Fragment
        fragmentManager.fragments.forEach { existingFragment ->
            if (existingFragment.isAdded && !existingFragment.isHidden) {
                transaction.hide(existingFragment)
            }
        }

        // 添加或显示目标Fragment
        if (fragment.isAdded) {
            transaction.show(fragment)
        } else {
            transaction.add(containerId, fragment)
        }

        transaction.safeCommit()
    }

    /**
     * 替换容器中的Fragment
     * @param containerId 容器ID
     * @param fragment 要替换的Fragment实例
     */
    fun replaceFragment(containerId: Int, fragment: Fragment) {
        fragmentManager.beginTransaction()
            .replace(containerId, fragment)
            .safeCommit()
    }

    /**
     * 显示Fragment
     * @param fragment 要显示的Fragment实例
     */
    fun showFragment(fragment: Fragment) {
        fragmentManager.beginTransaction()
            .show(fragment)
            .safeCommit()
    }

    /**
     * 隐藏Fragment
     * @param fragment 要隐藏的Fragment实例
     */
    fun hideFragment(fragment: Fragment) {
        if (!fragment.isHidden) {
            fragmentManager.beginTransaction()
                .hide(fragment)
                .safeCommit()
        }
    }

    /**
     * 移除Fragment
     * @param fragment 要移除的Fragment实例
     */
    fun removeFragment(fragment: Fragment) {
        if (fragment.isAdded) {
            fragmentManager.beginTransaction()
                .remove(fragment)
                .safeCommit()
        }
    }

    /**
     * 返回上一个Fragment
     * @return true: 成功返回; false: 栈底无法返回
     */
    fun popBackStack(): Boolean {
        return if (fragmentManager.backStackEntryCount > 0) {
            fragmentManager.popBackStack()
            true
        } else {
            false
        }
    }
}